package JavaFoundation.myLock;



import org.junit.jupiter.api.Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
/*
test1:结论。wait()/notify()不能脱离synchronized代码块执行   IllegalMonitorStateException不合法的异常
    2：一定要先wait,后notify.
lockawaitSingl：Condition的await和signal必须在lock中执行
    2：先等待后唤醒
lockSupport:无需要和关键字一起使用，并且unpark可以在这之前
 */

public class syncLocksupportTest {

    static Object objectlockA = new Object();
    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public void synchronizedWaitNotify(){
        new Thread(()->{
           // synchronized (objectlockA){
                System.out.println(Thread.currentThread().getName()+"/t"+"----com in");
                try {
                    objectlockA.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"/t"+"被唤醒");
           // }
        },"A").start();


        new Thread(()->{
           // synchronized (objectlockA){
                System.out.println(Thread.currentThread().getName()+"/t"+"----唤醒");
                objectlockA.notify();
          //  }
        },"B").start();

    }


    public void lockawaitSingl(){
        new Thread(()->{
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"/t"+"----com in");
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        },"A").start();

        new Thread(()->{
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName()+"/t"+"----唤醒");
            }finally {
                lock.unlock();
            }
        },"B").start();
    }


    public void test3(){
        Thread a = new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"/t"+"---com in");
            LockSupport.park();
            System.out.println(Thread.currentThread().getName()+"/t"+"---被唤醒了");
        },"A");
        a.start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"/t"+"---开始唤醒");
            LockSupport.unpark(a);
        },"A").start();
    }


}
